using System;
using JNPF.Basics.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JNPF.Utils;
using System.Transactions;

namespace JNPF.Basics.Logic
{
    public class PartnerBll
    {
        private PartnerIService service = new PartnerService();
        private UserIService userService = new UserService();

        private UserextendIService userextendService = new UserextendService();

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<PartnerEntity> GetInfo(int id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<PartnerEntity> GetInfoByMobilePhone(string mobilePhone)
        {
            try
            {
                return await service.GetInfoByMobilePhone(mobilePhone);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<PartnerEntity>> GetPageList(PartnerListQueryInput input)
        {
            try
            {
                return await service.GetPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<PartnerUpOutput>> GetPageListBySql(PartnerListQueryInput input)
        {
            try
            {
                return await service.GetPageListBySql(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(PartnerEntity entity)
        {
            try
            {
                entity.CreatorTime = DateTime.Now;
                //entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                //entity.CreatorUser = UserProvider.Instance.Get().UserName;
                entity.EnabledMark = 0;
                entity.DeleteMark = 0;
                return await service.Create(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }



        /// <summary>
        /// 审核加载
        /// </summary>
        /// <param name="cusEntity"></param>
        /// <param name="partner"></param>
        /// <returns></returns>
        public async Task Reviewer(PartnerEntity cusEntity, PartnerReviewer partner)
        {
            try
            {
                cusEntity.EnabledMark = 1; //审核通过
                                           //判断当前用户是否已经创建
                UserEntity entity = await userService.GetInfoByAccount(cusEntity.MobilePhone);

                List<UserRelationEntity> userRelationList = new List<UserRelationEntity>();
                //id为null
                if (entity == null || string.IsNullOrEmpty(entity.Id))
                {

                    #region 用户表单
                    entity = new UserEntity();
                    entity.RealName = cusEntity.RealName;
                    entity.Account = cusEntity.MobilePhone;
                    entity.MobilePhone = cusEntity.MobilePhone;
                    entity.Id = CommonHelper.Guid;
                    entity.QuickQuery = PinyinHelper.PinyinString(entity.RealName);
                    entity.Secretkey = CommonHelper.Guid.ToString();
                    entity.Password = string.IsNullOrEmpty(entity.Password) ? Md5Helper.md5("e10adc3949ba59abbe56e057f20f883e" + entity.Secretkey).ToLower() : Md5Helper.md5(entity.Password.ToLower() + entity.Secretkey).ToLower();
                    entity.CreatorTime = DateTime.Now;
                    entity.LastModifyTime = DateTime.Now;
                    entity.CreatorUserId = UserProvider.Instance.Get().UserId;

                    entity.RoleId = "2553d582c4c24f0fb5577ed79e6f3dfe"; //企业用户
                    entity.OrganizeId = "871fbe8b3fb146f7bed6c3a519e88a86";  //企业用户部门
                    entity.EnabledMark = 1;

                    var tup = WeChatHttpHelper.QrcodeCreateC(entity.Id);
                    entity.ShareImg = tup.Item1;


                    #endregion

                    #region 用户关系


                    //关联角色
                    if (entity.RoleId != null)
                    {
                        var roleId = new List<string>(entity.RoleId.Split(','));
                        foreach (var item in roleId)
                        {
                            UserRelationEntity relationEntity = new UserRelationEntity();
                            relationEntity.Id = CommonHelper.Guid;
                            relationEntity.ObjectType = "Role";
                            relationEntity.ObjectId = item;
                            relationEntity.SortCode = roleId.IndexOf(item);
                            relationEntity.UserId = entity.Id;
                            relationEntity.CreatorTime = entity.CreatorTime;
                            relationEntity.CreatorUserId = entity.CreatorUserId;
                            userRelationList.Add(relationEntity);
                        }
                    }
                    #endregion

                    #region 用户扩展表
                    UserextendEntity userextendEntity = new UserextendEntity();
                    userextendEntity.UserId = entity.Id;

                    if (string.IsNullOrEmpty(cusEntity.UserId))
                    {
                        userextendEntity.ParentPartnerUserId = "";
                    }
                    else
                    {
                        userextendEntity.ParentPartnerUserId = cusEntity.UserId;
                    }
                    userextendEntity.TotalPointsEarned = 0;
                    userextendEntity.TotalPointsSpent = 0;
                    userextendEntity.PointsPendingWithdrawal = 0;
                    userextendEntity.WithdrawPoints = 0;

                    //userextendEntity.ComConfig = partner.com  //TODO:审核的地方要存进去
                    //userextendEntity.First = partner.first;
                    //userextendEntity.Second = partner.second;
                    //userextendEntity.OnceMore = partner.onceMore;
                    userextendEntity.DrawProportion = partner.drawProportion;
                    userextendEntity.ComConfig = partner.comConfig;
                    userextendEntity.SortCode = 0;
                    userextendEntity.EnabledMark = 1;
                    userextendEntity.DeleteMark = 0;
                    userextendEntity.CreatorTime = DateTime.Now;
                    userextendEntity.CreatorUserId = UserProvider.Instance.Get().UserId;
                    #endregion

                    #region 添加合伙人消息推送信息
                    string str = "";
                    if (string.IsNullOrEmpty(entity.NickName))
                    {
                        string nameStr = "";
                        for (int i = 0; i < entity.RealName.Length - 1; i++)
                        {
                            nameStr += "*";
                        }
                        str = $"欢迎{entity.RealName.Substring(0, 1) + nameStr.Trim(',')}加入九士平台共创梦想";
                    }
                    else
                    {
                        str = $"欢迎{entity.NickName}加入九士平台共创梦想";
                    }
                    NewneedsEntity newneedsEntity = new NewneedsEntity();
                    newneedsEntity.Id = Guid.NewGuid().ToString();
                    newneedsEntity.Title = str;
                    newneedsEntity.Description = str;
                    newneedsEntity.UploadDate = DateTime.Now;
                    newneedsEntity.EnabledMark = 1;
                    newneedsEntity.UploadUser = "系统";
                    #endregion

                    await service.Create(cusEntity, entity, userRelationList, userextendEntity, newneedsEntity);
                }
                else
                {
                    //看看是否包含企业用户角色
                    if (!entity.RoleId.Contains("2553d582c4c24f0fb5577ed79e6f3dfe"))
                    {
                        #region  添加用户角色
                        //没有的话给他加一个
                        entity.RoleId += ",2553d582c4c24f0fb5577ed79e6f3dfe";
                        UserRelationEntity relationEntity = new UserRelationEntity();
                        relationEntity.Id = CommonHelper.Guid;
                        relationEntity.ObjectType = "Role";
                        relationEntity.ObjectId = "2553d582c4c24f0fb5577ed79e6f3dfe";
                        relationEntity.SortCode = 0;
                        relationEntity.UserId = entity.Id;
                        relationEntity.CreatorTime = entity.CreatorTime;
                        relationEntity.CreatorUserId = entity.CreatorUserId;
                        userRelationList.Add(relationEntity);

                        #endregion

                        #region 用户扩展
                        //查询下用户扩展表有没有数据，
                        UserextendEntity userextendEntity = await userextendService.GetInfoByUserId(entity.Id);
                        if (userextendEntity == null || userextendEntity.Id == 0)
                        {
                            //查询上级合伙人的扩展，赋值他的 合伙人机制
                            UserextendEntity parentuserextendEntity = await userextendService.GetInfoByUserId(cusEntity.UserId);

                            //如果不是合伙人就不创建
                            userextendEntity = new UserextendEntity();
                            userextendEntity.CreatorTime = DateTime.Now;
                            userextendEntity.UserId = entity.Id;
                            userextendEntity.ParentPartnerUserId = "";
                            userextendEntity.TotalPointsEarned = 0;
                            userextendEntity.WithdrawPoints = 0;
                            userextendEntity.TotalPointsSpent = 0;
                            userextendEntity.PointsPendingWithdrawal = 0;
                            userextendEntity.CreatorUserId = UserProvider.Instance.Get().UserId;
                            userextendEntity.CreatorUser = UserProvider.Instance.Get().UserName;
                            userextendEntity.DeleteMark = 0;
                            userextendEntity.ComConfig = parentuserextendEntity.ComConfig;
                            userextendEntity.DrawProportion = parentuserextendEntity.DrawProportion;
                        }
                        #endregion

                        #region 添加合伙人消息推送信息
                        string str = "";
                        if (string.IsNullOrEmpty(entity.NickName))
                        {
                            str = $"欢迎{entity.RealName}加入九士平台共创梦想";
                        }
                        else
                        {
                            str = $"欢迎{entity.NickName}加入九士平台共创梦想";
                        }
                        NewneedsEntity newneedsEntity = new NewneedsEntity();
                        newneedsEntity.Id = Guid.NewGuid().ToString();
                        newneedsEntity.Title = str;
                        newneedsEntity.Description = str;
                        newneedsEntity.UploadDate = DateTime.Now;
                        newneedsEntity.EnabledMark = 1;
                        newneedsEntity.UploadUser = "系统";
                        #endregion

                        //修改 用户  。修改 合伙人  添加扩展  添加合伙人推送

                        await service.CreateInsert(cusEntity, entity, userRelationList, userextendEntity, newneedsEntity);

                    }
                }

            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }



        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(int id, PartnerEntity entity)
        {
            try
            {
                entity.Id = id;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(PartnerEntity entity)
        {
            try
            {
                entity.DeleteMark = 1;
                entity.DeleteTime = DateTime.Now; ;
                entity.DeleteUserId = UserProvider.Instance.Get().UserId;

                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">过滤条件</param>
        /// <returns></returns>
        public async Task<List<PartnerEntity>> GetList(PartnerListQueryInput input)
        {
            try
            {
                return await service.GetList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


    }
}